﻿
using System;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
///  Generic Hierarchy Finite State Machine,
///  Hfsm is also a State of its super fsm
/// </summary>
/// <typeparam name="EntityController">may be playerController, enemyController, etc</typeparam>
public abstract class HFsm<StateId, EntityController> : State<StateId> {
	protected EntityController _controller;
	protected State<StateId>[] States { get; set; }

	protected HFsm(EntityController controller, StateId stateName, State<StateId> superFSM, StateFactory<StateId> factory) :
		base(stateName, superFSM, factory) {
		_controller = controller;
	}

	/// <summary>
	/// May be subFSMs, not only states, 
	/// to some extents, the fsm is also a state.
	/// </summary>
	public void AddSubState(State<StateId>[] states)
		=> States = states;
	public override void Update() {
		CurState.Update();
		base.Update();
	}

	/// <summary>
	/// Decide which SubState to run
	/// </summary>
	public override void Enter() {
		//Debug.Log($"{StateName},State num:{States.Count}");
		foreach (var s in States) {
			//Debug.Log($"choose {s.StateName}");
			var ret = s.ConditionToSelf?.Invoke() ?? false;
			if (ret) {
				CurState = s;
				CurState.Enter();
				break;
			}
		}
		//Debug
		//if (CurState == null)
		//PrintStateList();
	}
	protected void PrintStateList() {
		Debug.Log(GetAllStateName(this));
	}
	string GetAllStateName(State<StateId> state) {
		var ret = "";

		while (state != null) {
			ret += $"{state.StateName}->";
			state = state.CurState;
		}

		return ret;
	}

	public override void Exit() {
		CurState?.Exit();
		CurState = null;
	}
}

